package com.tms.gateway.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tms.common.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * Author：潘建冰
 * Package：com.tms.gateway.exception
 * Project：TaskManageSystem
 * name：GlobalExceptionHandler
 * Date：2025/3/25  10:53
 */
@Configuration
@Order(-1)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 设置响应的Content-Type
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        HttpStatusCode status;
        String message;
        Integer code;

        if (ex instanceof NotFoundException) {
            status = HttpStatus.NOT_FOUND;
            code = 404;
            message = "Service not found";
        } else if (ex instanceof ResponseStatusException responseStatusException) {
            status = responseStatusException.getStatusCode();
            code = status.value();
            message = responseStatusException.getMessage();
        } else {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            code = 500;
            message = "Gateway error: " + ex.getMessage();
        }

        response.setStatusCode(status);

        // 使用封装的Result返回统一格式
        Result<Object> result = Result.error(code, message);

        try {
            byte[] bytes = objectMapper.writeValueAsBytes(result);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            return Mono.error(e);
        }
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        System.out.println("e = " + e);
        return Result.error("系统异常，请联系管理员");
    }

}
